package cn.xf.districonfig.client.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.*;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Map;

public abstract class BeanRegistar {

    /**
     * Register Infrastructure Bean
     *
     * @param beanDefinitionRegistry {@link BeanDefinitionRegistry}
     * @param beanType               the type of bean
     * @param beanName               the name of bean
     */
    public static void registerInfrastructureBean(BeanDefinitionRegistry beanDefinitionRegistry,
                                                  String beanName,
                                                  Class<?> beanType) {

        if (!beanDefinitionRegistry.containsBeanDefinition(beanName)) {
            RootBeanDefinition beanDefinition = new RootBeanDefinition(beanType);
            beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
            beanDefinitionRegistry.registerBeanDefinition(beanName, beanDefinition);
        }

    }


    public static void registerBean(BeanDefinitionRegistry beanDefinitionRegistry,
                                    String beanName, String dependsOnBean,
                                    Class<?> beanType) {
        BeanDefinitionBuilder definition = BeanDefinitionBuilder
                .genericBeanDefinition(beanType);
        if (!StringUtils.isEmpty(dependsOnBean)) {
            definition.addDependsOn(dependsOnBean);
        }
        definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
        AbstractBeanDefinition beanDefinition = definition.getBeanDefinition();

        BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, beanType.getName(),
                new String[]{beanName});
        BeanDefinitionReaderUtils.registerBeanDefinition(holder, beanDefinitionRegistry);
    }

    public static Map<String, Object> getAnnotationAttributes(AnnotationMetadata metadata, String annotationName) {
        return metadata.getAnnotationAttributes(annotationName, true);
    }
}
